// pages/Designer.tsx
import React, { useState, useEffect, useRef } from 'react'
import PhoneMockup from './PhoneMockup'
import { Flex } from 'antd'
import { DropZone } from '../components/DropZone'
import { renderComponent } from '../utils/renderComponents'
import type { BodyItem, DesignerData } from '../types'
import { dragBus, propUpdateBus } from '../utils/dragBus'

interface DesignerProps {
  data: DesignerData
}

export const Designer: React.FC<DesignerProps> = ({ data }) => {
  console.log('>>> Designer data', data)

  const [body, setBody] = useState<BodyItem[]>(data.body || [])
  const [placeholderIndex, setPlaceholderIndex] = useState<number | null>(null)
  const [renderKey, setRenderKey] = useState(0) // 用于强制刷新组件的key
  const draggingIndexRef = useRef<number | null>(null)

  useEffect(() => {
    const handleDragStart = () => {
      if (dragBus.payload && dragBus.payload._index !== undefined) {
        draggingIndexRef.current = dragBus.payload._index as number
      }
    }

    const handleDragEnd = () => {
      draggingIndexRef.current = null
      // 更新renderKey来强制组件重新渲染
      setRenderKey(prev => prev + 1)
    }

    // 订阅属性更新事件
    const unsubscribe = propUpdateBus.subscribe(event => {
      const { index, data } = event
      const newBody = [...body]
      if (index >= 0 && index < newBody.length) {
        newBody[index] = { ...newBody[index], ...data }
        setBody(newBody)
      }
    })

    document.addEventListener('dragstart', handleDragStart)
    document.addEventListener('dragend', handleDragEnd)

    return () => {
      document.removeEventListener('dragstart', handleDragStart)
      document.removeEventListener('dragend', handleDragEnd)
      unsubscribe()
    }
  }, [body])

  const handleInsert = (index: number, item: BodyItem) => {
    console.log('>>> handleInsert', index, item)
    const newBody = [...body]
    newBody.splice(index, 0, item)
    setBody(newBody)
  }

  const handlePlaceholder = (index: number | null) => setPlaceholderIndex(index)

  const handleMove = (fromIndex: number, toIndex: number) => {
    if (fromIndex === toIndex) return

    const newBody = [...body]
    const [movedItem] = newBody.splice(fromIndex, 1)
    // 如果向前移动，由于删除了一个元素，目标索引需要调整
    const adjustedToIndex = fromIndex < toIndex ? toIndex - 1 : toIndex
    newBody.splice(adjustedToIndex, 0, movedItem)
    setBody(newBody)
  }

  // 把占位节点混入
  const renderList = () => {
    console.log('>>> renderList', body, placeholderIndex)
    const list: BodyItem[] = []
    body.forEach((it, i) => {
      // 为每个组件添加索引信息，用于移动操作
      const itemWithIndex = { ...it, _index: i }

      if (placeholderIndex === i) {
        list.push({ id: -Date.now(), type: 'placeholder', isPlaceholder: true })
      }
      list.push(itemWithIndex)
    })
    if (placeholderIndex === body.length) {
      list.push({ id: -Date.now(), type: 'placeholder', isPlaceholder: true })
    }
    return list.map((it, idx) => (
      <div key={it.id} data-index={idx}>
        {it.isPlaceholder ? (
          <div
            style={{
              width: 200,
              height: 30,
              border: '2px dashed #1677ff',
              background: 'rgba(22,119,255,.06)',
              borderRadius: 4,
              pointerEvents: 'none', // 防止占位符干扰鼠标事件
            }}
          />
        ) : (
          <div
            style={
              draggingIndexRef.current === it._index
                ? { border: '2px dashed #1677ff', borderRadius: 4 }
                : {}
            }
          >
            {/* 使用renderKey确保组件在拖拽结束后重新渲染 */}
            <div key={`${it.id}-${renderKey}`}>{renderComponent(it, idx)}</div>
          </div>
        )}
      </div>
    ))
  }

  return (
    <div style={{ display: 'flex', height: '100vh' }}>
      <div style={{ flex: 1, padding: 24 }}>
        <PhoneMockup>
          <div id="phone-inner" style={{ width: '100%', height: '100%', overflow: 'auto' }}>
            <Flex vertical align="center" gap={12}>
              // TODO 只写了搜索和公告两个
              {renderList()}
            </Flex>
          </div>
        </PhoneMockup>
        <DropZone
          body={body}
          onInsert={handleInsert}
          onPlaceholder={handlePlaceholder}
          onMove={handleMove}
        />
      </div>
      {/* <DropZone
        body={body}
        onInsert={handleInsert}
        onPlaceholder={handlePlaceholder}
        onMove={handleMove}
      /> */}
    </div>
  )
}
